<template>
  <div class="container">
    <div class="info">
      <div class="info-item">
        <h3>{{ $t('content_cover') }}</h3>
        <img
          v-if="form.newsType === 8"
          @click="preview(form)"
          :src="
            form.thumbs && form.thumbs.indexOf(';') > -1
              ? form.thumbs.split(';')[0]
              : form.thumbs || ''
          "
          :onerror="nonePic2"
          class="shortvideo-image pointer"
        />
        <img
          v-else
          @click="preview(form)"
          :src="
            form.thumbs && form.thumbs.indexOf(';') > -1
              ? form.thumbs.split(';')[0]
              : form.thumbs || ''
          "
          :onerror="nonePic1"
          class="news-image pointer"
        />
      </div>
      <div class="info-item">
        <h3>
          <span> {{ $t('content_information') }} </span>
          <el-button type="primary" size="small" @click="preview(form)">
            {{ $t('preview') }}
          </el-button>
        </h3>
        <p class="title" v-html="form.title"></p>
        <p>
          <span class="m-r-10"
            >{{ $t('release') }} : {{ form.authorName }}
          </span>
          <span>{{ $t('review') }} : {{ form.approveUserName }} </span>
        </p>
        <p>
          <span class="m-r-10">{{ newsTypeMap[form.newsType] }} </span>
          <span>{{ $t('release_time') }} : {{ form.releaseTime }} </span>
        </p>
        <p>
          <span
            >{{ $t('publisher_type') }} : {{ $t(authorTypeMap[form.authorType]) }}
          </span>
        </p>
        <p>
          <span>{{ $t('source') }} : {{ sourceTypeMap[form.sourceType] }} </span>
        </p>
        <p>
          <span>{{ $t('status') }} : {{ statusMap[form.isApprove] }} </span>
        </p>
        <p>
          <span>{{ $t('content_id') }} : {{ form.id }} </span>
        </p>
      </div>
      <div class="info-item">
        <p class="m-t-37">
          <span class="m-r-10"
            >{{ $t('like') }} : {{ form.praiseCount || 0 }}
          </span>
          <span class="m-r-10"
            >{{ $t('comment') }} : {{ form.reviewCount || 0 }}
          </span>
          <span class="m-r-10"
            >{{ $t('favorites') }} : {{ form.collectCount || 0 }}
          </span>
          <span class="m-r-10"
            >{{ $t('share') }} : {{ form.shareCount || 0 }}
          </span>
        </p>
        <p>
          <span>{{ $t('tag') }}: {{ form.typeTagsFlat || $t('none') }}</span>
        </p>
        <p>
          <span
            >{{ $t('special_page') }}:
            {{ form.subjectNameFlat || $t('none') }}</span
          >
        </p>
        <p>
          <span>{{ $t('topic') }}: {{ form.topicNameFlat || $t('none') }}</span>
        </p>
        <p>
          <span>{{ $t('score') }}: {{ form.score || $t('none') }}</span>
        </p>
        <p>
          <span
            >{{ $t('cumulative_exposure') }}:
            {{ form.totalShowPv || $t('none') }}</span
          >
        </p>
        <p>
          <span
            >{{ $t('cumulative_reading') }}:
            {{ form.totalReadCounts || $t('none') }}</span
          >
        </p>
        <p>
          <span
            >{{ $t('exposure_conversion_rate') }}:
            {{ form.showReadRate | percentageBydecima }}</span
          >
        </p>
      </div>
    </div>

    <el-row class="p-t-15">
      <el-col>
        <el-button
          :type="active == 'hour' ? 'primary' : ''"
          @click="changeTime('hour')"
        >
          {{ $t('by_hour') }}
        </el-button>
        <el-button
          :type="active == 'day' ? 'primary' : ''"
          @click="changeTime('day')"
        >
          {{ $t('by_day') }}
        </el-button>
        <el-date-picker
          v-model="datePicker1"
          class="w-240"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd"
        />
        <el-button @click="search"> {{ $t('filter') }} </el-button>
      </el-col>
      <el-col>
        <h3 class="total">
          <span class="m-r-10"
            >{{ $t('total_recommended_pv') }} :
            {{ totalObj.newsRecommendPV }}</span
          >
          <span class="m-r-10"
            >{{ $t('total_recommended_uv') }} :
            {{ totalObj.newsRecommendUV }}</span
          >
          <span class="m-r-10"
            >{{ $t('total_relevant_recommended_pv') }} :
            {{ totalObj.newsRelevantPV }}</span
          >
          <span class="m-r-10"
            >{{ $t('total_relevant_recommended_uv') }} :
            {{ totalObj.newsRelevantUV }}</span
          >
          <span class="m-r-10"
            >{{ $t('total_exposure_pv') }} : {{ totalObj.newsShowPV }}</span
          >
          <span class="m-r-10"
            >{{ $t('total_exposure_uv') }} : {{ totalObj.newsShowUV }}</span
          >
          <span class="m-r-10"
            >{{ $t('total_reading') }} : {{ totalObj.clickCount }}</span
          >
        </h3>
        <div id="one" :style="{ width: '100%', height: '480px' }"></div>
      </el-col>
      <el-col v-if="form.newsType == 3 || form.newsType == 8">
        <p>{{ $t('video_completion_rate') }}</p>
        <div id="two" :style="{ width: '100%', height: '480px' }"></div>
      </el-col>
    </el-row>

    <Preview
      v-if="previewData.newsType !== ''"
      v-model="previewData.newsType"
      :news-id="previewData.newsId"
      :lan="previewData.lan"
    />
  </div>
</template>

<script>
import { CONTENT_AUTHOR_TYPE_MAP } from '@/constants/index';
import { format } from 'date-fns';
import {
  getContentDetailApi,
  getNewsAnalyApi,
  getCompletionRateApi
} from '@/api/information-content-analysis';
import Preview from '@/components/preview/index.vue';
import echarts from 'echarts';

export default {
  components: {
    Preview
  },

  data() {
    return {
      datePicker1: [],
      newsId: null,
      active: 'hour',
      form: {},
      previewData: {
        newsId: '',
        newsType: '',
        title: '',
        time: ''
      },
      statusMap: {
        0: this.$t('audit_pending'),
        1: this.$t('audit_accept'),
        2: this.$t('drop_out'),
        3: this.$t('draft')
      },
      newsTypeMap: {
        1: this.$t('image_text'),
        2: this.$t('photo_album'),
        3: this.$t('video'),
        5: this.$t('micro_headlines'),
        8: this.$t('Short_video')
      },
      authorTypeMap: CONTENT_AUTHOR_TYPE_MAP,
      sourceTypeMap: {
        1: this.$t('reptile'),
        2: this.$t('background_editor'),
        3: this.$t('we_media'),
        4: 'APP',
      },
      nonePic1: `this.onerror=null;this.src="${require('@/assets/images/nopicture226x140.png')}"`,
      nonePic2: `this.onerror=null;this.src="${require('@/assets/images/nopicture366x550.png')}"`,
      listQuery: {
        newsId: null,
        beginTime: null,
        endTime: null,
        type: 'hour'
      },
      totalObj: {
        newsRecommendPV: 0,
        newsRecommendUV: 0,
        newsRelevantPV: 0,
        newsRelevantUV: 0,
        newsShowPV: 0,
        newsShowUV: 0,
        hotIndex: 0,
        clickCount: 0
      }
    };
  },

  filters: {
    percentageBydecima(val) {
      if (!val || val == 0) {
        return 0;
      }

      return `${(val * 100).toFixed(2)}%`;
    }
  },

  created() {
    this.newsId = this.$route.query.newsId;
    this.init();
  },

  mounted() {
    const { language, newsId, path } = this.$route.query;
    if (language) {
      this.handleSetLanguage(language);
      this.$router.replace({
        path,
        query: {
          newsId
        }
      });
    }
  },

  methods: {
    handleSetLanguage(lang) {
      this.$i18n.locale = lang;
      this.$store.dispatch('app/setLanguage', lang);
    },

    async init() {
      const { code, data } = await getContentDetailApi({ id: this.newsId });
      if (code == 200) {
        this.form = data || {};
        this.changeTime('hour');
      }
    },

    resetTotalObj() {
      this.totalObj = {
        newsRecommendPV: 0,
        newsRecommendUV: 0,
        newsRelevantPV: 0,
        newsRelevantUV: 0,
        newsShowPV: 0,
        newsShowUV: 0,
        hotIndex: 0,
        clickCount: 0
      };
    },

    async search() {
      const { datePicker1, listQuery, active } = this;
      const [beginTime, endTime] = datePicker1 || [null, null];
      this.listQuery = { ...listQuery, beginTime, endTime, type: active };

      this.resetTotalObj();

      const { code, data } = await getNewsAnalyApi(this.listQuery);
      if (code == 200) {
        if (this.form.newsType == 3 || this.form.newsType == 8) {
          this.getPlaybackRate();
        }

        if (!data || data.length == 0) {
          this.$nextTick(() => {
            this.upDateEchart('one', null, null, null);
          });
        } else {
          let series = [];
          const legend = [
            this.$t('recommend_pv'),
            this.$t('recommended_uv'),
            this.$t('related_recommendations_pv'),
            this.$t('related_recommendations_uv'),
            this.$t('exposure_pv'),
            this.$t('exposure_uv'),
            this.$t('real_heat'),
            this.$t('reading')
          ];
          const date = [];
          const map = {
            newsRecommendPV: [],
            newsRecommendUV: [],
            newsRelevantPV: [],
            newsRelevantUV: [],
            newsShowPV: [],
            newsShowUV: [],
            hotIndex: [],
            clickCount: []
          };

          const totalObj = {
            newsRecommendPV: 0,
            newsRecommendUV: 0,
            newsRelevantPV: 0,
            newsRelevantUV: 0,
            newsShowPV: 0,
            newsShowUV: 0,
            hotIndex: 0,
            clickCount: 0
          };

          data.forEach(item => {
            date.push(item.dt);
            Object.keys(map).forEach(key => {
              totalObj[key] += Number(item[key]) || 0;
              map[key].push(item[key]);
            });
          });

          series = Object.keys(map).map((key, index) => ({
            data: map[key],
            name: legend[index],
            type: 'line'
          }));

          this.totalObj = totalObj;

          this.$nextTick(() => {
            this.upDateEchart('one', legend, series, date);
          });
        }
      }
    },

    async getPlaybackRate() {
      const { code, data } = await getCompletionRateApi({
        newsId: this.newsId
      });
      if (code == 200) {
        if (
          data &&
          data.completionRateDetails &&
          data.completionRateDetails.length > 0
        ) {
          const date = [];
          const arr = [];
          const duration = Number(data.duration) || 0;
          const completionRateDetails = data.completionRateDetails || [];

          // 大于视频时长的不显示
          completionRateDetails.forEach(item => {
            if (item.second <= duration) {
              date.push(`${item.second}s`);
              arr.push(item.rate);
            }
          });

          const series = [
            {
              data: arr,
              type: 'line'
            }
          ];

          this.$nextTick(() => {
            this.upDateEchart('two', null, series, date, '{value} %');
          });
        } else {
          this.$nextTick(() => {
            this.upDateEchart('two', null, null, null, '{value} %');
          });
        }
      }
    },

    upDateEchart(dom, legend, series, date, formatter = '{value}') {
      const myChart = echarts.init(document.getElementById(dom));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,

        title: {
          show: !series || series.length == 0,
          textStyle: {
            color: '#909399',
            fontSize: 14,
            fontWeight: 400
          },
          text: this.$t('no_data_available'),
          left: 'center',
          top: 'center'
        },

        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },

        legend: {
          data: legend
        },

        grid: {
          left: 60,
          right: 60
        },

        xAxis: [
          {
            type: 'category',
            data: date
          }
        ],

        yAxis: [
          {
            type: 'value',
            axisLabel: {
              formatter
            }
          }
        ],

        series
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    preview({ id, newsType }) {
      this.previewData = { ...this.previewData, newsId: id, newsType };
    },

    changeTime(key) {
      const { releaseTime, id: newsId } = this.form;
      const beginTime = releaseTime && releaseTime.slice(0, 10);
      const endTime = format(new Date(), 'yyyy-MM-dd');
      this.active = key;

      if (key == 'hour') {
        this.listQuery = {
          newsId,
          beginTime,
          endTime: beginTime,
          type: 'hour'
        };
        this.datePicker1 = [];
      } else {
        this.listQuery = {
          newsId,
          beginTime,
          endTime,
          type: 'day'
        };
        this.datePicker1 = [beginTime, endTime];
      }
      this.search();
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 15px;

  .top-search {
    margin: 10px 0;

    label {
      font-size: 12px;
      font-weight: 400;
      margin-right: 5px;
    }
  }

  .info {
    display: flex;
  }

  .news-image {
    width: 200px;
    height: 140px;
    object-fit: cover;
  }

  .shortvideo-image {
    width: 167px;
    height: 250px;
    object-fit: cover;
  }

  .pointer {
    cursor: pointer;
  }

  h3 {
    line-height: 2;
    margin-bottom: 13px;
  }

  .info-item {
    min-width: 170px;
    margin-right: 30px;

    p {
      font-size: 18px;
      line-height: 2;
    }
  }

  .m-t-37 {
    margin-top: 50px;
  }

  .pointer {
    cursor: pointer;
  }

  .title {
    max-width: 500px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
  }

  .total {
    padding: 15px 0;
    font-size: 18px;
    line-height: 2;
  }
}
</style>
